﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Configuration;
using System.Web;
using System.Security.Cryptography;

namespace WechatUtility
{
    public class Utilities
    {
        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }

        /// <summary>
        /// 获得文件保存路径
        /// </summary>
        /// <param name="FileName">文件名称</param>
        /// <returns>扩展名</returns>
        public static string GetFileSavePath()
        {
            string savePath = "../Upload/" + DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
            return savePath;
        }

        /// <summary>
        /// 返回文件扩展名，不含“.”
        /// </summary>
        /// <param name="_filepath">文件全名称</param>
        /// <returns>string</returns>
        public static string GetFileExt(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return "";
            }
            if (_filepath.LastIndexOf(".") > 0)
            {
                return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名，不含“.”
            }
            return "";
        }

        #region 生成随机码
        /// <summary>
        /// 生成日期随机码
        /// </summary>
        /// <returns></returns>
        public static string GetRamCode()
        {
            #region
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            #endregion
        }
        /// <summary>
        /// 生成随机数
        /// </summary>
        ///  <param name="len">长度</param>
        /// <returns>随机数</returns>
        public static string GetRandom(int len)
        {
            char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < len; i++)
            {
                newRandom.Append(constant[rd.Next(9)]);
            }
            return newRandom.ToString();
        }
        #endregion

        #region 获得当前绝对路径
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            return HttpContext.Current.Server.MapPath(strPath);
        }
        #endregion

        /// <summary>
        /// 删除上传的文件(及缩略图)
        /// </summary>
        /// <param name="_filepath"></param>
        public static void DeleteUpFile(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return;
            }
            string fullpath = GetMapPath(_filepath); //原图
            if (File.Exists(fullpath))
            {
                File.Delete(fullpath);
            }
            if (_filepath.LastIndexOf("/") >= 0)
            {
                string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
                string fullTPATH = GetMapPath(thumbnailpath); //宿略图
                if (File.Exists(fullTPATH))
                {
                    File.Delete(fullTPATH);
                }
            }
        }

        /// <summary>
        /// 生成Html
        /// </summary>
        /// <param name="template">模版文件路径</param>
        /// <param name="path">生成的文件目录</param>
        /// <param name="htmlname">生成的文件名</param>
        /// <param name="dic">字典(替换字符,内容)</param>
        /// <param name="message">异常消息</param>
        /// <returns></returns>
        public static bool CreateHtml(string template, string path, string htmlname, Dictionary<string, string> dic, ref string message)
        {
            bool result = false;
            string templatepath = System.Web.HttpContext.Current.Server.MapPath(template);
            string htmlpath = System.Web.HttpContext.Current.Server.MapPath(path);
            string htmlnamepath = Path.Combine(htmlpath, htmlname);
            Encoding encode = Encoding.UTF8;
            StringBuilder html = new StringBuilder();

            try
            {
                //读取模版
                html.Append(File.ReadAllText(templatepath, encode));
            }
            catch (FileNotFoundException ex)
            {
                message = ex.Message;
                return false;
            }

            foreach (KeyValuePair<string, string> d in dic)
            {
                //替换数据
                html.Replace(string.Format("${0}$", d.Key), d.Value);
            }

            try
            {
                //写入html文件
                if (!Directory.Exists(htmlpath))
                    Directory.CreateDirectory(htmlpath);
                File.WriteAllText(htmlnamepath, html.ToString(), encode);
                result = true;
            }
            catch (IOException ex)
            {
                message = ex.Message;
                return false;
            }

            return result;
        }
    }
}